package com.trainingcloud.action.document;

import java.io.File;

import org.apache.struts2.ServletActionContext;

import com.trainingcloud.action.BaseSessionAction;
import com.trainingcloud.dao.DocumentDAO;
import com.trainingcloud.dao.FavoriteDAO;
import com.trainingcloud.entity.Document;
import com.trainingcloud.exception.DAOException;
import com.trainingcloud.exception.SystemException;

public class DeleteDocumentAction extends BaseSessionAction 
{
	private String documentIds;
	
	public DeleteDocumentAction() throws SystemException 
	{
		super();
	}

	@Override
	public String callWithSession() throws DAOException, SystemException 
	{
		if(documentIds.isEmpty())
		{
			return "Empty document id list.";
		}
		
		String[] documentIdList = documentIds.split(",");
		
		DocumentDAO documentDAO = new DocumentDAO();
		for(int i=1; i<=documentIdList.length; i++)
		{
			int documentId = Integer.parseInt(documentIdList[i-1]);
			
			Document document = documentDAO.getDocumentById(documentId);
			if(document==null)
			{
				return "Invalid document id.";
			}
			documentDAO.deleteDocument(documentId);
			
			File file = new File(ServletActionContext.getServletContext().getRealPath("/documents/"+document.getFileLocation()));
			if(file.isFile() && file.exists())
			{
				if(!file.delete())
				{
					return "Delete document file failed.";
				}
			}
		}
		return null;
	}

	public String getDocumentIds() {
		return documentIds;
	}

	public void setDocumentIds(String documentIds) {
		this.documentIds = documentIds;
	}

}
